package com.ming.easyDevelop.utils;

import com.ming.easyDevelop.entity.baseEnum.DateTimePatternEnum;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 時間工具類,用於格式化時間或者解析時間
 */
public class DateUtils {
    private static final Object lock = new Object();
    private static Map<String,ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();

    private static SimpleDateFormat getSdf(final String pattern){
        ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
        if(null == tl){
            synchronized (lock){
                tl = sdfMap.get(pattern);
                if(null == tl){
                    tl = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
                    sdfMap.put(pattern,tl);
                }
            }
        }
        return tl.get();
    }

    /**
     * 格式化時間
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date,String pattern){
        if(date == null) return null;
        return getSdf(pattern).format(date);
    }

    /**
     * 解析時間
     * @param dateStr
     * @param pattern
     * @return
     */
    public static Date parse(String dateStr,String pattern){
        try {
            if(dateStr == null) return null;
            return getSdf(pattern).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
